import styles from '@/pages/Search/components/CardList.less';
import {
    calendarUsingGET,
    subjectsDetailUsingGET,
} from '@/services/otherworldly-station-backend/BangumiController';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { Button, Card, Divider, Image, List, message, Modal, Spin, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import {
    addFilmTelevisionUsingPOST,
    deleteFilmTelevisionUsingPOST
} from "@/services/otherworldly-station-backend/FilmTelevisionController";

// 链接中转，通过其他网站重定向展示图片
const getImages = (_url: string | undefined) => {
    if (_url !== undefined) {
        let _u = _url.substring(7);
        return 'https://images.weserv.nl/?url=' + _u;
    }
};
// 每日放映
const DailyScreen: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [modalOpen, setModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [isWatched, setIsWatched] = useState<boolean>(false);
    const [movieItem, setMovieItem] = useState<API.BangumiSubjectDetailVO>({});
    const [monRecords, setMonRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);
    const [tueRecords, setTueRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);
    const [wedRecords, setWedRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);
    const [thuRecords, setThuRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);
    const [friRecords, setFriRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);
    const [satRecords, setSatRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);
    const [sunRecords, setSunRecords] = useState<API.BangumiSearchSubjectSmallVO[]>([]);

    useEffect(() => {
        loadingData(0, 50);
    }, []);

    // 获取用户信息
    const loadingData = async (start: number, count: number) => {
        setLoading(true);
        return calendarUsingGET().then((res) => {
            console.log(res);
            if (res.code === 0 && res.data) {
                res.data.forEach((weeklyItem) => {
                    var items = weeklyItem.items;
                    var weekly = weeklyItem.weekdays;
                    if (weekly && weekly[0].id === '1') {
                        setMonRecords(items || []);
                    } else if (weekly && weekly[0].id === '2') {
                        setTueRecords(items || []);
                    } else if (weekly && weekly[0].id === '3') {
                        setWedRecords(items || []);
                    } else if (weekly && weekly[0].id === '4') {
                        setThuRecords(items || []);
                    } else if (weekly && weekly[0].id === '5') {
                        setFriRecords(items || []);
                    } else if (weekly && weekly[0].id === '6') {
                        setSatRecords(items || []);
                    } else if (weekly && weekly[0].id === '7') {
                        setSunRecords(items || []);
                    }
                });
                setLoading(false);
            }
        });
    };

    /**
     * 获取影片详情
     * @param subject_id
     */
    const showAnimeDetail = (subject_id: number) => {
        setLoading(true);
        setIsWatched(false);
        setMovieItem({});
        // 获取影片详情
        subjectsDetailUsingGET({ subject_id }).then((res) => {
            if (res.code === 0) {
                let data = res.data as API.BangumiSubjectDetailVO;
                console.log(data);
                if (data.watchStatus) {
                    // 有值说明已存入影视列表
                    setIsWatched(true);
                }
                setMovieItem(data);
                setModalOpen(true);
                setLoading(false);
            }
            if (res.code === 40400) {
                message.warning(res.message);
            }
        });
    };

    /**
     * 不想看 click事件
     * @param id
     */
    const deleteMyFavorite = (id: number) => {
        // 取消收藏
        setSubmitLoading(true);
        // 取消收藏，删除本地记录
        deleteFilmTelevisionUsingPOST({ id })
            .then((res) => {
                if (res.code === 0) {
                    message.warning('影片已从您的影视列表中移除');
                }
            })
            .finally(() => {
                setModalOpen(false);
                setSubmitLoading(false);
            });
    };

    /**
     * 加入收藏
     * @param watchStatus
     */
    const addMyFavorite = (watchStatus: number) => {
        setSubmitLoading(true);
        // 加入收藏
        addFilmTelevisionUsingPOST({
            id: movieItem.id,
            name: movieItem.name,
            description: movieItem.summary,
            images: JSON.stringify(movieItem.images),
            tags: JSON.stringify(movieItem.tags),
            type: movieItem.subType,
            releaseDate: movieItem.airDate,
            airWeekDate: movieItem.airWeekDate,
            score: movieItem.score,
            totalEpisodes: movieItem.totalEpisodes,
            watchStatus,
        })
            .then((res) => {
                console.log(res);
                if (res.code === 0) {
                    message.success('成功加入影片列表');
                }
            })
            .finally(() => {
                setSubmitLoading(false);
                setModalOpen(false);
            });
    };

    return (
        <PageContainer>
            <Spin spinning={submitLoading}>
                <Modal
                    width="500px"
                    centered
                    open={modalOpen}
                    onCancel={() => setModalOpen(false)}
                    footer={
                        isWatched
                            ? [
                                  <Button
                                      key="dislike"
                                      onClick={() => deleteMyFavorite(movieItem.id as number)}
                                  >
                                      不想看
                                  </Button>,
                              ]
                            : [
                                  <Button key="back" onClick={() => setModalOpen(false)}>
                                      取消
                                  </Button>,
                                  <Button
                                      key="watched"
                                      type="default"
                                      style={{ backgroundColor: '#ed6d3d', color: '#fff' }}
                                      onClick={() => addMyFavorite(3)}
                                  >
                                      看过
                                  </Button>,
                                  <Button
                                      key="watchings"
                                      type="primary"
                                      style={{ backgroundColor: '#ed6d46', color: '#fff' }}
                                      onClick={() => addMyFavorite(2)}
                                  >
                                      在看
                                  </Button>,
                                  <Button
                                      key="wishWatch"
                                      style={{ backgroundColor: '#e94829', color: '#fff' }}
                                      onClick={() => addMyFavorite(1)}
                                  >
                                      想看
                                  </Button>,
                              ]
                    }
                >
                    <ProCard
                        direction="column"
                        ghost
                        gutter={{
                            xs: 1,
                            sm: 1,
                            md: 1,
                            lg: 1,
                            xl: 1,
                            xxl: 2,
                        }}
                        style={{ overflow: 'auto', marginTop: '15px' }}
                        className={styles.coverCardList}
                    >
                        <ProCard style={{ textAlign: 'center' }}>
                            <Image width={200} src={getImages(movieItem.images?.medium)} />
                        </ProCard>
                        <ProCard>
                            <h2>
                                <b>{movieItem.name}</b>
                                <span
                                    style={{
                                        marginLeft: '10px',
                                        fontSize: '18px',
                                    }}
                                >
                                    {movieItem.score ? movieItem.score : 0}
                                </span>
                            </h2>
                            {movieItem.tags?.map((item, index) => {
                                return index < 6 ? (
                                    <Tag
                                        key={item}
                                        bordered={true}
                                        color="#fa5822"
                                        style={{ marginBottom: '10px' }}
                                    >
                                        {item}
                                    </Tag>
                                ) : null;
                            })}
                            <Divider style={{ margin: '0 0 10px 0' }} />
                            <div style={{ height: 'auto' }}>{movieItem.summary}</div>
                        </ProCard>
                    </ProCard>
                </Modal>
            </Spin>
            <Spin spinning={loading}>
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期一</div>}
                    bordered
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 6,
                        xl: 8,
                        xxl: 8,
                    }}
                    dataSource={monRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期二</div>}
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }}
                    bordered
                    dataSource={tueRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期三</div>}
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }}
                    bordered
                    dataSource={wedRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期四</div>}
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }}
                    bordered
                    dataSource={thuRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期五</div>}
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }}
                    bordered
                    dataSource={friRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期六</div>}
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }}
                    bordered
                    dataSource={satRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
                <List
                    style={{ margin: '10px 0' }}
                    header={<div style={{ fontWeight: 700, fontSize: '22px' }}>星期七</div>}
                    grid={{
                        gutter: 24,
                        xs: 1,
                        sm: 2,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }}
                    bordered
                    dataSource={sunRecords}
                    renderItem={(item) => (
                        <List.Item style={{ paddingTop: '15px' }}>
                            <Card
                                hoverable
                                cover={<img alt={item.name} src={item?.images?.large} />}
                                onClick={() => {
                                    showAnimeDetail(item.id as number);
                                }}
                            >
                                <Card.Meta title={item.name} />
                            </Card>
                        </List.Item>
                    )}
                />
            </Spin>
        </PageContainer>
    );
};

export default DailyScreen;
